package com.wanshi.interceptor;

import com.alibaba.fastjson.JSON;
import com.wanshi.utils.JwtUtil;
import com.wanshi.utils.Result;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class AuthenticationFilter extends HandlerInterceptorAdapter {

    @Autowired
    private  JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isLogin = false;
        // 获取请求头 Authorization: Bearer jwtToken
        final String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 截取获取jwtToken
             final String token = authHeader.substring(7);
             // 解析
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null) {
                if( (Boolean) claims.get("isLogin") ) {
                    // 已登录
                    isLogin = true;
                        }
                    }
                }
        if(!isLogin) {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString( Result.nologin()  ));
            //response.setStatus(401);
            //response.getWriter().write("未通过身份认证");

        }
        return isLogin;
    }
}
